package com.utils.updateapp;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;

/**
 * @author SongJiaTai
 * @description: 应用版本更新工具类
 * @date :2019/5/22 10:39
 */
public class UpdateUtils {
    private static UpdateUtils updateUtils = null;
    private Context context;
    //请求更新接口地址
    private final String API_URL = "https://api.jinlejia.com/" + "5354/version/getVersion/%s/%s";
    //更新接口实体类
    private UpdateBean updateBean;
    // 下载应用的进度条
    private ProgressDialog progressDialog;
    //外存sdcard存放路径
    private final String FILE_PATH;
    // 下载应用存放全路径
    private static String FILE_NAME;
    //仅仅应用存储名称
    private static String ONLY_FILE_NAME;
    // 推荐更新每次打开应用提示一次
    public static int OPEN_TAG = 1;
    //系统下载类
    private DownloadManager downloadManager;
    //后台下载任务标识
    private long enqueue;

    private UpdateUtils(File file) {
//        FILE_PATH = file + File.separator + "AutoUpdate" + File.separator;
        FILE_PATH = Environment.getExternalStorageDirectory() + File.separator + "AutoUpdate" + File.separator;
    }

    public static synchronized UpdateUtils getInstance(Context context) {
        if (updateUtils == null) {
            updateUtils = new UpdateUtils(context.getExternalCacheDir());
        }
        updateUtils.context = context;
        return updateUtils;
    }

    /**
     * 检查更新方法
     *
     * @param versionCode 当前app版本号
     */
    private void innerCheck(String versionCode, final UpdateListener listener) {
        String url = String.format(API_URL, "inhome_android", versionCode);
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (listener != null) {
                            listener.showMessage("网络连接失败");
                        }
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        updateBean = JSON.parseObject(response, UpdateBean.class);
                        ONLY_FILE_NAME = "inhome" + updateBean.getData().getVersion() + ".apk";
                        FILE_NAME = FILE_PATH + ONLY_FILE_NAME;
                        Log.d("wwe", "onResponse: " + updateBean.getData().getIsForce());
                        if (updateBean.getData().getIsForce() == 1) {   //强制更新
                            showUpdataDialog();
                        } else if (updateBean.getData().getIsForce() == 0) { //推荐更新
                            showNoticeDialog();
                        } else {
                            if (listener != null) {
                                listener.showMessage("您已经是最新版本！");
                            }
                        }

                    }
                });
    }


    public void checkAndUpdate(String versionCode) {
        innerCheck(versionCode, null);
    }

    public void checkAndUpdateAndShowMessage(String versionCode, UpdateListener listener) {
        innerCheck(versionCode, listener);
    }

    public interface UpdateListener {
        void showMessage(String message);
    }


    /**
     * 强制更新提示框
     */
    protected void showUpdataDialog() {
        MandatoryUpdateDialog mandatoryUpdateDialog = new MandatoryUpdateDialog(context, "版本升级", "更新内容：\n" + updateBean.getData().getContent(), "下次再说", "体验新版", 2);

        mandatoryUpdateDialog.setConfirmListener(new MandatoryUpdateDialog.OnConfirmListener() {
            @Override
            public void confirm() {
                File file = new File(FILE_NAME);
                if (file.exists()) {
                    file.delete();
                }
                if (!file.exists()) {
                    showDownloadDialog();
                } else {
                    if (file.length() == 0) {
                        file.delete();
                        showDownLoadNotice();
                        return;
                    }

                    long modified = file.lastModified();
                    long seconds = TimeUnit.MILLISECONDS.toSeconds(modified);
                    long millis = System.currentTimeMillis();
                    long nowSeconds = TimeUnit.MILLISECONDS.toSeconds(millis);
                    long speedSeconds = nowSeconds - seconds;
                    if (speedSeconds > 30) { //如果上个文件下载的时间超过30秒
                        //重新去下载？
                        //return
                    }
                    installApp();
                }
            }
        });
        mandatoryUpdateDialog.setCancelable(false);
        mandatoryUpdateDialog.show();
    }


    /**
     * 强制更新下载进度条
     */
    public void showDownloadDialog() {

        progressDialog = new ProgressDialog(context);
        progressDialog.setTitle("正在下载...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();
        FileDownloader.getImpl().create(updateBean.getData().getUrl())
                .setPath(FILE_NAME)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        progressDialog.setProgress((soFarBytes * 100 / totalBytes));

                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        progressDialog.dismiss();
                        installApp();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        progressDialog.dismiss();
                        Toast.makeText(context, "下载暂停", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        progressDialog.dismiss();
                        Toast.makeText(context, "网络失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                        progressDialog.dismiss();
                        Toast.makeText(context, "已有下载任务", Toast.LENGTH_SHORT).show();
                    }
                }).start();
    }

    /**
     * 安装apk
     */
    private void installApp() {
        File appFile = new File(FILE_NAME);
        if (!appFile.exists()) {
            return;
        }

        Intent intent = new Intent();

        intent.setAction(Intent.ACTION_VIEW);
        Uri _uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            _uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", appFile);
        } else {
            _uri = Uri.fromFile(appFile);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.setDataAndType(_uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 推荐更新提示弹窗
     */
    private void showNoticeDialog() {
        MandatoryUpdateDialog mandatoryUpdateDialog = new MandatoryUpdateDialog(context, "优化更新", "更新内容：\n" + updateBean.getData().getContent(), "下次再说", "体验新版", 1);
        mandatoryUpdateDialog.setCancelListener(new MandatoryUpdateDialog.OnCancelListener() {
            @Override
            public void cancel() {
                OPEN_TAG = 2;
            }
        });
        mandatoryUpdateDialog.setConfirmListener(new MandatoryUpdateDialog.OnConfirmListener() {
            @Override
            public void confirm() {
                File file = new File(FILE_NAME);
                if (file.exists()) {
                    file.delete();
                }
                if (!file.exists()) {
                    Toast.makeText(context, "inhome:开始后台下载更新文件...", Toast.LENGTH_SHORT).show();
                    showDownLoadNotice();
                } else {
                    if (file.length() == 0) {
                        file.delete();
                        Toast.makeText(context, "inhome:开始后台下载更新文件...", Toast.LENGTH_SHORT).show();
                        showDownLoadNotice();
                        return;
                    }
                    installApp();
                }
            }
        });
        mandatoryUpdateDialog.setCancelable(false);
        mandatoryUpdateDialog.show();
    }

    /**
     * 推荐更新通知栏下载进度
     */
    private void showDownLoadNotice() {
        downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        String downUrl = updateBean.getData().getUrl();

        //创建下载请求对象
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));
        request.setAllowedOverRoaming(false);
        File file = new File(FILE_PATH, "inhome" + updateBean.getData().getVersion() + ".apk");
        request.setDestinationUri(Uri.fromFile(file));
        /* request.setDestinationInExternalPublicDir(FILE_PATH,"inhome" + updateBean.getData().getVersion() + ".apk");*/
        //设置允许使用的网络类型
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setMimeType("application/vnd.android.package-archive");//机型适配
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setTitle("inhome更新");
        request.setDescription("正在下载中...");
        request.setVisibleInDownloadsUi(true);
        if (downloadManager == null) {
            downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        }
        if (downloadManager != null) {
            try{
                enqueue = downloadManager.enqueue(request);
            }catch (SecurityException e){
                File f = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                f = new File(f, "Android");
                f = new File(f, "data");
                f = new File(f, "files");
                f = new File(f, Environment.DIRECTORY_DOWNLOADS);
                if (!f.exists()) {
                    f.mkdirs();
                }
                request.setDestinationUri(Uri.fromFile(f));
                enqueue = downloadManager.enqueue(request);
            }
        }
        context.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    }

    /**
     * 检查apk后台下载状态码
     */
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(enqueue);
        Cursor cursor = downloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED://下载暂停
                    break;
                case DownloadManager.STATUS_PENDING://下载延迟
                    break;
                case DownloadManager.STATUS_RUNNING://正在下载
                    break;
                case DownloadManager.STATUS_SUCCESSFUL://下载完成
                    installApp();
                    cursor.close();
                    context.unregisterReceiver(receiver);
                    break;
                case DownloadManager.STATUS_FAILED://下载失败
                    Toast.makeText(context, "下载失败", Toast.LENGTH_LONG).show();
                    cursor.close();
                    context.unregisterReceiver(receiver);
                    break;
            }
        }
        cursor.close();
    }

    /**
     * 接收通知栏下载发出的广播
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };
}
